<template>
    <div class="settings-view">
        <h1 class="view-title">{{ $t('settings.title') }}</h1>

        <div class="settings-grid">
            <!-- 用户信息 -->
            <div class="settings-card" id="user-info-card">
                <!-- ... 用户信息卡片内容保持不变 ... -->
                <h2 class="card-title">{{ $t('settings.userInfo') }}</h2>
                <div class="avatar-section">
                    <el-avatar
                        :size="80"
                        :src="editableUserInfo.avatarPreview || getAvatarPath(editableUserInfo.avatar || userStore.user?.avatar)"
                        @error="() => true"
                        @click="triggerFileUpload" 
                        class="clickable-avatar"
                        title="点击修改头像" 
                    >
                         <img :src="defaultAvatar" />
                     </el-avatar>
                     <input 
                        type="file" 
                        ref="fileInput" 
                        style="display: none;" 
                        accept="image/jpeg,image/png,image/gif,image/webp"
                        @change="handleFileChange" 
                     />
                </div>
                <div class="settings-list">
                     <div class="setting-item">
                        <span class="item-label">{{ $t('settings.username') }}</span>
                        <div class="item-control">
                             <el-input v-model="editableUserInfo.username" size="small" :placeholder="$t('placeholders.enterUsername')" class="inline-input"/>
                        </div>
                    </div>
                     <div class="setting-item">
                        <span class="item-label">{{ $t('settings.role') }}</span>
                        <div class="item-control">
                             <span class="item-value">{{editableUserInfo.role }}</span>
                        </div>
                    </div>
                    <div class="setting-item">
                        <span class="item-label">{{ $t('settings.email') }}</span>
                        <div class="item-control">
                             <el-input v-model="editableUserInfo.email" size="small" :placeholder="$t('placeholders.enterEmail')" class="inline-input"/>
                        </div>
                    </div>
                    <div class="setting-item">
                        <span class="item-label">{{ $t('settings.nickname') }}</span>
                        <div class="item-control">
                            <el-input v-model="editableUserInfo.nickname" size="small" :placeholder="$t('placeholders.enterNickname')" class="inline-input"/>
                        </div>
                    </div>
                </div>
                <div class="user-info-actions">
                    <el-button @click="cancelUserProfileEdit">{{ $t('common.cancel') }}</el-button>
                    <el-button type="primary" size="small" @click="saveUserProfile">{{ $t('settings.saveUserInfo') }}</el-button>
                </div>
            </div>

            <!-- 账号设置 -->
            <div class="settings-card">
                <h2 class="card-title">{{ $t('settings.accountSettings') }}</h2>
                <div class="settings-list">
                    <div class="setting-item">
                        <span class="item-label">{{ $t('settings.locationName') }}</span>
                        <div class="item-control">
                            <el-input v-model="editableLocationName" size="small" :placeholder="$t('placeholders.currentLocationName')" style="width: 180px;" :disabled="!isEditingLocation"/>
                            <el-button type="primary" size="small" v-if="!isEditingLocation && isAdmin" @click="startEditLocation" class="location-edit-btn">
                                <el-icon><Edit /></el-icon>
                            </el-button>
                            <el-button type="primary" size="small" v-else-if="isEditingLocation" @click="updateLocationName" class="location-edit-btn">
                                {{ $t('common.save') }}
                            </el-button>
                            <el-button v-if="isEditingLocation" size="small" @click="cancelEditLocation" class="location-edit-btn">
                                {{ $t('common.cancel') }}
                            </el-button>
                        </div>
                    </div>

                    <div class="setting-item clickable" @click="navigateTo('修改密码')">
                        <span class="item-label">{{ $t('settings.changePassword') }}</span>
                        <div class="item-control">
                        <el-icon class="arrow-icon"><ArrowRight /></el-icon>
                        </div>
                    </div>
                    <div class="setting-item clickable" @click="navigateTo('隐私设置')">
                        <span class="item-label">{{ $t('settings.privacySettings') }}</span>
                        <div class="item-control">
                        <el-icon class="arrow-icon"><ArrowRight /></el-icon>
                        </div>
                    </div>
                    <div class="setting-item logout-item clickable" @click="logout">
                        <span class="item-label logout-label">{{ $t('common.logout') }}</span>
                        <div class="item-control">
                        <el-icon class="logout-icon"><SwitchButton /></el-icon>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 系统设置 -->
            <div class="settings-card">
                <h2 class="card-title">{{ $t('settings.systemSettings') }}</h2>
                <div class="settings-list">

                    <div class="setting-item">
                        <span class="item-label">{{ $t('settings.systemName') }}</span>
                        <div class="item-control">
                        <el-input v-model="settings.systemName" size="small" :placeholder="$t('placeholders.systemName')" style="width: 150px; text-align: right;"/>
                    </div>
                    </div>
                    <!-- 从通知设置移动过来的选项 -->
                    <div class="setting-item">
                        <span class="item-label">{{ $t('settings.itemExpiryReminder') }}</span>
                        <div class="item-control">
                        <el-switch v-model="settings.notifications.expiration"/>
                        </div>
                    </div>
                    <div class="setting-item">
                        <span class="item-label">{{ $t('settings.inventoryWarning') }}</span>
                        <div class="item-control">
                        <el-switch v-model="settings.notifications.lowStock"/>
                        </div>
                    </div>
                    <div class="setting-item">
                        <span class="item-label">{{ $t('settings.dataUpdateReminder') }}</span>
                        <div class="item-control">
                        <el-switch v-model="settings.notifications.updates"/>
                    </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 操作按钮 -->
        <div class="settings-actions">
            <el-button @click="resetSettings">{{ $t('settings.resetSettings') }}</el-button>
            <el-button type="primary" @click="saveSettings">{{ $t('settings.saveSettings') }}</el-button>
        </div>

        <!-- 添加修改密码组件 -->
        <ChangePasswordModal 
          :visible="changePasswordVisible" 
          @close="changePasswordVisible = false"
          @success="handlePasswordChanged" 
        />
    </div>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted, watch, computed } from 'vue';
import { ElMessage, ElMessageBox, ElAvatar, ElInput } from 'element-plus';
import { ArrowRight, Moon, Sunny, CircleCheck, Warning, Bell, SwitchButton, Edit } from '@element-plus/icons-vue';
import { useRouter } from 'vue-router';
import { useUserStore } from '@/stores/user';
import { usePermissionStore } from '@/stores/permission';
import { useSettingsStore } from '@/stores/settings';
import { locationsApi } from '@/utils/apiService';
import i18n from '@/i18n';
import ChangePasswordModal from '@/components/settings/ChangePasswordModal.vue'; // 导入修改密码组件

const router = useRouter();
const userStore = useUserStore();
const permissionStore = usePermissionStore();
const settingsStore = useSettingsStore();

const defaultAvatar = ref('https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png');

// Reactive state for editable user info
const editableUserInfo = reactive({
    username: '',
    email: '',
    role: '',
    nickname: '',
    avatar: '',
    avatarFile: null,
    avatarPreview: null,
    originalAvatar: '' // 存储原始头像，用于取消时恢复
});

// Watch for changes in userStore.user to initialize/update editableUserInfo
watch(() => userStore.user, (newUser) => {
    if (newUser) {
        editableUserInfo.username = newUser.username || '';
        editableUserInfo.email = newUser.email || '';
        editableUserInfo.nickname = newUser.nickname || '';
        editableUserInfo.avatar = newUser.avatar || '';
        editableUserInfo.role = newUser.role || '';
        editableUserInfo.originalAvatar = newUser.avatar || ''; // 保存原始头像
    }
}, { immediate: true, deep: true }); // immediate to run on mount, deep if user is nested

const isDarkMode = ref(window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches);

const settings = reactive({
                systemName: '家居物品管理系统',
    theme: 'auto',
                iCloudSync: true,
                notifications: {
                    expiration: true,
                    lowStock: true,
                    updates: false
    },
    language: 'zh-CN',
    password: '',
    privacyLevel: 'standard',
});

let originalSettings = {};

const languageOptions = [
    { value: 'zh-CN', label: '简体中文' },
    { value: 'en-US', label: 'English' },
];

const displayRole = computed(() => {
  const roleId = userStore.user?.roleId;
  switch (roleId) {
    case 1: return i18n.global.t('roles.admin');
    case 2: return i18n.global.t('roles.manager');
    case 3: return i18n.global.t('roles.member');
    case 0: return i18n.global.t('roles.guest');
    default: return userStore.user?.roleName || i18n.global.t('roles.unknown');
  }
});

const updateTheme = () => {
    if (settings.theme === 'auto') {
        isDarkMode.value = window.matchMedia('(prefers-color-scheme: dark)').matches;
            } else {
        isDarkMode.value = settings.theme === 'dark';
            }
    document.documentElement.classList.toggle('dark', isDarkMode.value);
};

const handleSystemThemeChange = (e) => {
    if (settings.theme === 'auto') {
        isDarkMode.value = e.matches;
        document.documentElement.classList.toggle('dark', isDarkMode.value);
    }
};

watch(() => settings.theme, updateTheme);
            
// 判断当前用户是否有管理权限或查看用户权限
const isAdmin = computed(() => {
  // 获取当前位置ID
  const locationId = selectedLocationId.value || localStorage.getItem('currentLocationId');
  if (!locationId) {
    console.log('无法获取位置ID，用户无权限');
    return false;
  }
  
  // 使用权限检查：有管理位置用户权限或有查看用户权限
  const canManage = permissionStore.canManageLocationUsers(locationId);
  const canViewUsers = permissionStore.canViewUserPermissions(locationId);
  
  // 记录日志
  console.log('用户权限检查:', {
    locationId, 
    canManage, 
    canViewUsers, 
    userRole: userStore.user?.roleId
  });
  
  // 允许有管理权限或查看用户权限的用户修改位置名称
  return canManage || canViewUsers;
});

// 位置相关数据
const userLocations = ref([]);
const selectedLocationId = ref(null);
const editableLocationName = ref('');
const locationLoading = ref(false);
const isEditingLocation = ref(false);
const originalLocationName = ref('');

// 获取用户所有位置
const fetchUserLocations = async () => {
    try {
        locationLoading.value = true;
        // 获取当前用户ID
        const userId = userStore.user?.id;
        if (!userId) {
            console.error('未找到用户ID，无法获取位置信息');
            return;
        }

        const response = await locationsApi.getUserLocations(userId);
        if (response && response.code === 200 && response.data) {
            userLocations.value = response.data;
            
            // 如果有位置，默认选中当前位置或第一个
            if (userLocations.value.length > 0) {
                // 尝试从路由或localStorage获取当前位置ID
                const currentLocationId = router.currentRoute.value.query?.locationId || 
                                        localStorage.getItem('currentLocationId');
                
                if (currentLocationId) {
                    // 检查当前位置ID是否在用户位置列表中
                    const exists = userLocations.value.some(location => location.id == currentLocationId);
                    if (exists) {
                        selectedLocationId.value = currentLocationId;
                        const location = userLocations.value.find(loc => loc.id == currentLocationId);
                        if (location) {
                            editableLocationName.value = location.name;
                        }
                    } else {
                        // 如果不存在，选择第一个
                        selectedLocationId.value = userLocations.value[0].id;
                        editableLocationName.value = userLocations.value[0].name;
                    }
                } else {
                    // 没有当前位置ID，选择第一个
                    selectedLocationId.value = userLocations.value[0].id;
                    editableLocationName.value = userLocations.value[0].name;
                }
            }
        }
    } catch (error) {
        console.error('获取用户位置出错:', error);
        ElMessage.error('获取位置信息失败');
    } finally {
        locationLoading.value = false;
    }
};

// 开始编辑位置名称
const startEditLocation = () => {
    // 添加调试日志
    console.log('开始编辑位置名称，当前状态:', {
        selectedLocationId: selectedLocationId.value,
        locationFromStorage: localStorage.getItem('currentLocationId'),
        isAdmin: isAdmin.value,
        userLocations: userLocations.value,
        permissionStore: permissionStore
    });
    
    // 检查权限
    if (!isAdmin.value) {
        ElMessage.error(i18n.global.t('messages.insufficientPermissions'));
        return;
    }
    
    originalLocationName.value = editableLocationName.value;
    isEditingLocation.value = true;
};

// 取消编辑位置名称
const cancelEditLocation = () => {
    editableLocationName.value = originalLocationName.value;
    isEditingLocation.value = false;
};

// 更新位置名称
const updateLocationName = async () => {
    // 添加调试日志
    console.log('尝试更新位置名称:', {
        selectedLocationId: selectedLocationId.value,
        editableLocationName: editableLocationName.value,
        originalLocationName: originalLocationName.value,
        isAdmin: isAdmin.value
    });
    
    // 再次检查权限
    if (!isAdmin.value) {
        ElMessage.error(i18n.global.t('messages.insufficientPermissions'));
        isEditingLocation.value = false;
        editableLocationName.value = originalLocationName.value;
        return;
    }

    if (!selectedLocationId.value) {
        // 尝试从localStorage获取位置ID
        const locationIdFromStorage = localStorage.getItem('currentLocationId');
        console.log('尝试从localStorage获取位置ID:', locationIdFromStorage);
        
        if (locationIdFromStorage) {
            selectedLocationId.value = locationIdFromStorage;
        } else {
            ElMessage.warning('未找到当前位置');
            isEditingLocation.value = false;
            return;
        }
    }

    if (!editableLocationName.value.trim()) {
        ElMessage.warning('位置名称不能为空');
        return;
    }

    if (editableLocationName.value === originalLocationName.value) {
        isEditingLocation.value = false;
        return;
    }

    try {
        locationLoading.value = true;
        
        // 确保位置ID是整数
        const locationId = typeof selectedLocationId.value === 'string' 
            ? parseInt(selectedLocationId.value, 10) 
            : selectedLocationId.value;
            
        console.log('发送API请求更新位置名称:', {
            locationId: locationId,
            newName: editableLocationName.value.trim()
        });

        const response = await locationsApi.updateLocation(
            locationId, 
            { name: editableLocationName.value.trim() }
        );
        
        console.log('更新位置名称API响应:', response);

        if (response && response.code === 200) {
            ElMessage.success(i18n.global.t('messages.locationNameUpdated'));
            isEditingLocation.value = false;
            
            // 刷新位置列表
            await fetchUserLocations();
            
            // 设置标记以便在返回时刷新Dashboard
            if (router.currentRoute && router.currentRoute.value) {
                router.currentRoute.value.meta.fromSettings = true;
            }
            
            // 更新localStorage中的位置名称
            try {
                // 刷新当前位置显示
                const updatedLocations = JSON.parse(localStorage.getItem('userLocations') || '[]');
                const locationIndex = updatedLocations.findIndex(loc => loc.id == locationId);
                
                if (locationIndex !== -1) {
                    updatedLocations[locationIndex].name = editableLocationName.value.trim();
                    localStorage.setItem('userLocations', JSON.stringify(updatedLocations));
                }
            } catch (error) {
                console.error('更新localStorage中的位置名称失败:', error);
            }
            
            // 询问用户是否要刷新页面以应用更改
            ElMessageBox.confirm(
                i18n.global.t('messages.locationUpdateRefresh'),
                i18n.global.t('messages.locationUpdateTitle'),
                {
                    confirmButtonText: i18n.global.t('dialogs.refresh'),
                    cancelButtonText: i18n.global.t('dialogs.refreshLater'),
                    type: 'info',
                }
            ).then(() => {
                window.location.reload();
            }).catch(() => {
                // 用户选择稍后刷新，不执行任何操作
            });
        } else {
            ElMessage.error(response?.msg || '更新位置名称失败');
        }
    } catch (error) {
        console.error('更新位置名称出错:', error);
        ElMessage.error(`更新位置名称失败: ${error.message || '未知错误'}`);
    } finally {
        locationLoading.value = false;
    }
};

onMounted(() => {
    originalSettings = JSON.parse(JSON.stringify(settings));
    loadSettings();
    updateTheme();
    window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', handleSystemThemeChange);
    if (!userStore.user) {
        userStore.getCurrentUser();
    }
    // Initialize editableUserInfo if user is already available
    if (userStore.user) {
         editableUserInfo.username = userStore.user.username || '';
         editableUserInfo.email = userStore.user.email || '';
         editableUserInfo.nickname = userStore.user.nickname || '';
         editableUserInfo.avatar = userStore.user.avatar || '';
    }
    
    // 获取用户位置
    fetchUserLocations();
});

onUnmounted(() => {
    window.matchMedia('(prefers-color-scheme: dark)').removeEventListener('change', handleSystemThemeChange);
    
    // 清理可能存在的头像预览URL
    if (editableUserInfo.avatarPreview) {
        URL.revokeObjectURL(editableUserInfo.avatarPreview);
    }
});

const loadSettings = () => {
    console.log('加载设置...');
    const savedSettings = localStorage.getItem('appSettings');
    if (savedSettings) {
        const parsedSettings = JSON.parse(savedSettings);
        const validKeys = Object.keys(settings);
        for (const key of validKeys) {
            if (parsedSettings.hasOwnProperty(key)) {
                 if (key === 'notifications' && typeof parsedSettings[key] === 'object') {
                    Object.assign(settings.notifications, parsedSettings.notifications);
                 } else {
                    settings[key] = parsedSettings[key];
                 }
            }
        }
    }
    originalSettings = JSON.parse(JSON.stringify(settings));
};

const saveSettings = () => {
    console.log('保存设置:', JSON.parse(JSON.stringify(settings)));
    
    // 检查语言是否改变
    const oldLanguage = settingsStore.language;
    const newLanguage = settings.language;
    
    // 保存设置到localStorage
    localStorage.setItem('appSettings', JSON.stringify(settings));
    
    // 更新settings store中的语言设置
    settingsStore.setLanguage(newLanguage);
    
    // 使用i18n的消息
    const successMsg = i18n.global.t('messages.settingsSaved');
    ElMessage.success(successMsg);
    
    // 保存原始设置
    originalSettings = JSON.parse(JSON.stringify(settings));
    
    // 由于我们已经在App.vue中实现了自动语言切换，这里不再需要提示用户刷新页面
};

const resetSettings = () => {
    const defaultSettings = {
        systemName: '家居物品管理系统',
        theme: 'auto',
        iCloudSync: true,
        notifications: {
            expiration: true,
            lowStock: true,
            updates: false
        },
        language: 'zh-CN',
        password: '',
        privacyLevel: 'standard',
    };
    
    // 检查语言是否改变
    const oldLanguage = localStorage.getItem('language');
    const newLanguage = defaultSettings.language;
    
    Object.assign(settings, JSON.parse(JSON.stringify(defaultSettings)));
    updateTheme();
    
    // 使用i18n消息
    const resetMsg = i18n.global.t('messages.settingsReset');
    ElMessage.info(resetMsg);
    
    // 保存设置到localStorage
    localStorage.setItem('appSettings', JSON.stringify(settings));
    localStorage.setItem('language', settings.language);
    originalSettings = JSON.parse(JSON.stringify(settings));
    
    // 如果语言改变了，提示刷新
    if (oldLanguage !== newLanguage) {
        settingsStore.setLanguage(newLanguage);
        
        ElMessageBox.confirm(
            i18n.global.t('dialogs.languageChangeRefreshMessage'),
            i18n.global.t('dialogs.languageChangeTitle'),
            {
                confirmButtonText: i18n.global.t('dialogs.refresh'),
                cancelButtonText: i18n.global.t('dialogs.refreshLater'),
                type: 'warning',
            }
        ).then(() => {
            window.location.reload();
        });
    }
};

// 添加修改密码对话框状态
const changePasswordVisible = ref(false);

// 导航到不同设置页面
const navigateTo = (target) => {
  if (target === '修改密码') {
    // 显示修改密码对话框
    changePasswordVisible.value = true;
  } else if (target === '隐私设置') {
    // 处理隐私设置
    ElMessage.info('隐私设置功能暂未实现');
  }
};

// 处理密码修改成功
const handlePasswordChanged = () => {
  ElMessage.success('密码修改成功');
};

const logout = async () => {
    try {
        await userStore.logout();
    ElMessage.success(i18n.global.t('messages.logoutSuccess'));
    router.push('/login');
    } catch (error) {
        ElMessage.error(i18n.global.t('messages.logoutFailed'));
        console.error('Logout failed:', error);
    }
};

// 文件上传相关
const fileInput = ref(null);

// 修改头像方法
const triggerFileUpload = () => {
    // 直接触发文件输入框点击事件
    fileInput.value.click();
};

// 处理文件选择变化
const handleFileChange = (event) => {
    const file = event.target.files[0];
    if (!file) return;
    
    // 首次选择头像时，保存原始头像
    if (!editableUserInfo.originalAvatar) {
        editableUserInfo.originalAvatar = editableUserInfo.avatar;
    }
    
    // 验证文件大小 (限制为2MB)
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
        ElMessage.error('头像图片大小不能超过 2MB!');
        // 重置文件输入框
        event.target.value = '';
        return;
    }
    
    // 验证文件类型
    const isValidType = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'].includes(file.type);
    if (!isValidType) {
        ElMessage.error('头像只能是 JPG/PNG/GIF/WEBP 格式!');
        // 重置文件输入框
        event.target.value = '';
        return;
    }
    
    // 创建临时URL用于立即预览
    if (editableUserInfo.avatarPreview) {
        URL.revokeObjectURL(editableUserInfo.avatarPreview); // 清理旧的预览URL
    }
    editableUserInfo.avatarPreview = URL.createObjectURL(file);
    
    // 保存文件对象，稍后在保存用户信息时一起上传
    editableUserInfo.avatarFile = file;
    
    ElMessage.success(i18n.global.t('messages.avatarSelected'));
};

// --- User Profile Functions ---
const saveUserProfile = async () => {
    // Basic validation (example)
    if (!editableUserInfo.username) {
        ElMessage.error('用户名不能为空');
        return;
    }
    // Check if data actually changed (optional but good practice)
    const changed = editableUserInfo.username !== userStore.user?.username ||
                    editableUserInfo.email !== userStore.user?.email ||
                    editableUserInfo.nickname !== userStore.user?.nickname ||
                    editableUserInfo.avatarFile !== null; // 检查是否有头像更改

    if (!changed) {
        ElMessage.info('用户信息未更改');
        return;
    }

    console.log('Saving user profile:', JSON.parse(JSON.stringify(editableUserInfo)));
    
    try {
        // 准备更新的用户数据
        const userData = {
            id: userStore.user.id, // 确保包含用户ID
            username: editableUserInfo.username,
            email: editableUserInfo.email,
            nickname: editableUserInfo.nickname
        };
        
        // 如果有头像文件，将其添加到userData中
        if (editableUserInfo.avatarFile) {
            // 创建FormData对象供userStore处理
            const formData = new FormData();
            formData.append('avatar', editableUserInfo.avatarFile);
            userData.avatarFormData = formData;
            
            // 显示上传指示
            ElMessage.info('正在处理头像...');
        }
        
        // 使用userStore的方法更新用户信息（包括头像）
        const success = await userStore.updateUser(userData);
        
        if (success) {
            ElMessage.success('用户信息已更新');
            
            // 如果头像更新成功，更新原始头像
            if (editableUserInfo.avatarFile && userStore.user.avatar) {
                editableUserInfo.originalAvatar = userStore.user.avatar;
            }
            
            // 重置头像变量以避免再次提交
            editableUserInfo.avatarFile = null;
            
            // 释放临时URL并清除预览
            if (editableUserInfo.avatarPreview) {
                URL.revokeObjectURL(editableUserInfo.avatarPreview);
                editableUserInfo.avatarPreview = null;
            }
        } else {
            ElMessage.error('更新用户信息失败');
        }
    } catch (error) {
        console.error('更新用户信息失败:', error);
        ElMessage.error(`更新用户信息失败: ${error.message || '未知错误'}`);
    }
};

const getAvatarPath = (avatar) => {
    if (!avatar) {
        return defaultAvatar.value;
    }
    
    // 如果已经是完整URL（包含http或https），直接返回
    if (typeof avatar === 'string' && (avatar.startsWith('http') || avatar.startsWith('data:'))) {
        return avatar;
    }
    
    // 如果是文件名，添加到images路径
    if (typeof avatar === 'string') {
        return `/images/${avatar}`;
    }
    
    // 如果是对象且包含url属性
    if (typeof avatar === 'object' && avatar.url) {
        return avatar.url;
    }
    
    return defaultAvatar.value;
};

// 添加取消编辑功能
const cancelUserProfileEdit = () => {
    // 重置表单数据为当前用户信息
    if (userStore.user) {
        editableUserInfo.username = userStore.user.username || '';
        editableUserInfo.email = userStore.user.email || '';
        editableUserInfo.nickname = userStore.user.nickname || '';
        editableUserInfo.avatar = editableUserInfo.originalAvatar || userStore.user.avatar || ''; // 恢复原始头像值
    }
    
    // 清理头像预览
    if (editableUserInfo.avatarPreview) {
        URL.revokeObjectURL(editableUserInfo.avatarPreview);
        editableUserInfo.avatarPreview = null;
    }
    
    // 清理头像文件数据
    editableUserInfo.avatarFile = null;
    
    // 重置文件输入框，确保能够再次选择同一文件
    if (fileInput.value) {
        fileInput.value.value = '';
    }
    
    ElMessage.info('已取消编辑');
};

</script>

<style scoped>
.settings-view {

    height: 100vh;
    width: 100%;
    max-width: none;
    margin: 0;
    box-sizing: border-box;
    font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
    color: #333;
    overflow: hidden;
    display: flex;
    flex-direction: column;
}

/* --- Dark Mode --- */
.dark-mode .settings-view {
    color: #ddd;
}
.dark-mode .settings-card {
    background-color: #2c2c2c;
    border-color: #444;
}
.dark-mode .view-title,
.dark-mode .card-title,
.dark-mode .item-label,
.dark-mode .item-value,
.dark-mode .logout-label,
.dark-mode .app-name,
.dark-mode .app-version,
.dark-mode .copyright,
.dark-mode .el-avatar,
.dark-mode .edit-avatar-btn {
    color: #eee;
}
.dark-mode .setting-item {
    border-bottom-color: #444;
}
.dark-mode .setting-item:hover {
    background-color: #383838;
}
.dark-mode .el-button {
    /* Optional: Adjust button styles for dark mode if needed */
}
.dark-mode .el-button--primary {
    /* Optional: Adjust primary button styles for dark mode if needed */
}
.dark-mode .el-input__inner,
.dark-mode .el-select .el-input__inner {
    background-color: #3a3a3a !important;
    border-color: #555 !important;
    color: #eee !important;
}
.dark-mode .el-select-dropdown {
    background-color: #2c2c2c;
    border-color: #444;
}
.dark-mode .el-select-dropdown__item {
    color: #ddd;
}
.dark-mode .el-select-dropdown__item.hover,
.dark-mode .el-select-dropdown__item:hover {
    background-color: #383838;
}
.dark-mode .el-switch.is-checked .el-switch__core {
    border-color: #409EFF;
    background-color: #409EFF;
}
.dark-mode .el-switch__core {
    background: #555;
    border-color: #555;
}
.dark-mode .about-card .copyright {
     color: #aaa;
}

/* --- General Layout --- */
.view-title {
    font-size: 50px;
    font-weight: 600;
    margin-bottom: 20px;
    color: #1a1a1a;
}

.settings-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(350px, 1fr));
    gap: 24px;
    flex: 1;
    overflow: hidden;
    margin-bottom: 15px;
    grid-auto-rows: minmax(min-content, max-content);
}

.settings-card {
    background-color: #fff;
    border-radius: 16px;
    padding: 20px 24px;
    box-shadow: 0 6px 16px rgba(0, 0, 0, 0.1);
    border: 1px solid #e8e8e8;
    transition: box-shadow 0.3s ease;
    overflow-y: auto;
    height: 500px;
    max-height: 500px;
    display: flex;
    flex-direction: column;
}

.settings-card:hover {
     box-shadow: 0 6px 16px rgba(0, 0, 0, 0.1);
}

.card-title {
    font-size: 30px;
    font-weight: 600;
    margin-bottom: 16px;
    color: #333;
    border-bottom: 2px solid #f0f0f0;
    padding-bottom: 10px;
}

.settings-list {
    margin-top: 10px;
    flex-grow: 1;
    overflow-y: auto;
}

/* --- Setting Item Layout --- */
.setting-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 12px 0;
    border-bottom: 1px solid #f0f0f0;
    transition: background-color 0.2s ease;
    min-height: 46px;
}

.setting-item:last-child {
    border-bottom: none;
}

.setting-item.clickable {
    cursor: pointer;
}

.setting-item.clickable:hover {
    background-color: #f9f9f9;
}

.item-label {
    font-size: 18px;
    color: #444;
    margin-right: 15px;
    flex-shrink: 0;
}

.item-control {
    margin-left: auto;
    display: flex;
    align-items: center;
    justify-content: flex-end;
}

.item-value {
    font-size: 20px;
    color: #666;
    text-align: right;
}

/* Ensure Element Plus components align well */
.item-control .el-select,
.item-control .el-input,
.item-control .el-switch {
    /* Add specific alignment/margin if needed, but align-items on parent helps */
}

/* Icons */
.arrow-icon, .logout-icon {
    color: #aaa;
    font-size: 16px;
    margin-left: 8px;
}

/* Specific Item Adjustments */
.logout-item {
    margin-top: 15px;
    padding-top: 15px;
    border-top: 1px solid #f0f0f0;
    border-bottom: none;
}

.logout-label {
    color: #f56c6c;
    font-weight: 500;
}

.logout-icon {
    color: #f56c6c;
}

/* About Card */
.about-card {
    max-height: none;
    height: 85%;
}

.about-content {
    display: flex;
    flex-direction: column;
    align-items: center;
    text-align: center;
    padding-top: 5px;
}

.app-icon-placeholder {
    width: 50px;
    height: 50px;
    background-color: #eee;
    border-radius: 12px;
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 12px;
    color: #aaa;
    margin-bottom: 10px;
}

.app-name {
    font-size: 16px;
    font-weight: 600;
    margin-bottom: 3px;
    color: #333;
}

.app-version {
    font-size: 13px;
    color: #888;
    margin-bottom: 10px;
}

.copyright {
    font-size: 12px;
    color: #aaa;
}

/* Action Buttons */
.settings-actions {
    display: flex;
    justify-content: flex-end;
    margin-top: 0;
    margin-bottom: 20px;
    padding-top: 15px;
    border-top: 1px solid #f0f0f0;
    position: relative;
    bottom: 80px;
}

.settings-actions .el-button {
    margin-left: 15px;
    min-width: 100px;
    font-size: 14px;
}

#user-info-card {
    grid-column: 1;
    grid-row: 1;
    display: flex;
    flex-direction: column;
}

.avatar-section {
    display: flex;
    flex-direction: column;
    align-items: center;
    margin-bottom: 15px;
    padding-top: 5px;
}

.clickable-avatar {
    cursor: pointer;
    transition: opacity 0.2s ease;
}

.clickable-avatar:hover {
    opacity: 0.85;
}

/* Style for inline inputs */
.item-control .inline-input {
    --el-input-border-color: transparent;
    --el-input-hover-border-color: var(--el-border-color-hover);
    --el-input-focus-border-color: var(--el-color-primary);
    box-shadow: none !important;
    background-color: transparent;
    padding-left: 0;
    padding-right: 0;
    text-align: right;
}

.item-control .inline-input .el-input__wrapper {
    background-color: transparent !important;
    box-shadow: none !important;
    padding: 1px 0;
}

.item-control .inline-input.is-focus .el-input__wrapper {
    box-shadow: 0 0 0 1px var(--el-color-primary) inset !important;
}

:deep(.inline-input .el-input__inner) {
    text-align: right;
    font-size: 18px;
}

.user-info-actions {
    margin-top: 15px;
    padding-top: 10px;
    border-top: 1px solid #f0f0f0;
    display: flex;
    justify-content: flex-end;
}

.dark-mode .item-control .inline-input {
    --el-input-border-color: transparent;
    --el-input-hover-border-color: #555;
    --el-input-focus-border-color: #409EFF;
    color: #eee;
}
.dark-mode .item-control .inline-input .el-input__wrapper {
     background-color: transparent !important;
}
.dark-mode :deep(.inline-input .el-input__inner) {
    color: #eee;
    font-size: 18px;
}
.dark-mode .user-info-actions {
    border-top-color: #444;
}

.location-actions {
    margin-top: 10px;
    margin-bottom: 20px;
    padding-bottom: 10px;
    border-bottom: 1px solid #eee;
}

.location-edit-btn {
    margin-left: 8px;
}

.dark-mode .location-actions {
    border-bottom-color: #444;
}
</style>